package com.xl.minyue.tc2.until;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;

public class DingDing {
    //正式环境
    private static final String nonceStr="Nowd@dd123";
    private static final String agentId="185300717";
    private static final String corpId="dingd8706cc08c78b8bd35c2f4657eb6378f";
    private static final String corpSecret="hgRrIZMRfJZi-D7iej_JNafKbAeDekQDyeZEARpnPGyII47Ee9zoyziRGvAFFQVg";

    /*private static String nonceStr;
    private static String agentId;
    private static String corpId;
    private static String corpSecret;

    public DingDing(String nonceStr,String agentId,String corpId,String corpSecret) {
        this.nonceStr=nonceStr;
        this.agentId=agentId;
        this.corpId=corpId;
        this.corpSecret=corpSecret;
    }*/

/*//测试环境
    private static final String nonceStr="Nowd@dd123";
    private static final String agentId="172323564";
    private static final String corpId="ding7d10dc8a95f6ec2335c2f4657eb6378f";
    private static final String corpSecret="0afukzc19Rm-7Pu-iACDKOp2zacZHC7h1SObTTAqxKMEeoADHmgjd0ehDKwL5E78";
   */
    /*
   *  //测试环境
   * 前端工程
    corpId="ding5ffacc42b902630435c2f4657eb6378f";
    corpSecret="BV3sIYjATNgAko7CaQWAfSbOq8HO8pUd2AkNsj2ru5kTZfqE3VDrlhVf16MKd3HO";
    nonceStr="Nowd@dd123";
    agentId="121765099";
    熊孩子团队
    corpId="ding7d10dc8a95f6ec2335c2f4657eb6378f";
    agentId:172323564
    corpSecret="0afukzc19Rm-7Pu-iACDKOp2zacZHC7h1SObTTAqxKMEeoADHmgjd0ehDKwL5E78";
   *太仓:
   * agentId="185300717";
    corpId="dingd8706cc08c78b8bd35c2f4657eb6378f";
    corpSecret="hgRrIZMRfJZi-D7iej_JNafKbAeDekQDyeZEARpnPGyII47Ee9zoyziRGvAFFQVg";
   * */


    public static void main(String[] args) {
        String access_token = getAccess_token();
        System.out.println(access_token+"<----access_token");
       /* String url="https://oapi.dingtalk.com/user/simplelist?access_token="+access_token+"&department_id="+1;
        String result =getData(url);
        System.out.println("2222222222222222--->"+result);
        String url2="https://oapi.dingtalk.com/department/get?access_token="+access_token+"&id="+1;
        String result2 =getData(url2);
        System.out.println("33333333333333333--->"+result2);*/
       /* Emp empDetail = getEmpDetail("0651490869921242");
        String userInfo = JSON.toJSONString(empDetail);
        System.out.println(userInfo);
        Emp emp = new Emp();
        System.out.println(empDetail.toString()+"------");*/

    }


    //获取access_token
    public static String getAccess_token() {
        String url="https://oapi.dingtalk.com/gettoken?corpid="+corpId+"&corpsecret="+corpSecret;
        String result =getData(url);
        //System.out.println("111111111111111111111--->"+result);
        JSONObject map = JSON.parseObject(result);
        return map.getString("access_token");
    }

    public static String getData(String url) {
        //System.out.println(url+"--url-------");
        String result = "";
        BufferedReader in = null;
        try {
            URL getUrl = new URL(url);
            URLConnection connection = getUrl.openConnection();
            connection.setRequestProperty("Charset", "UTF-8");
            connection.setRequestProperty("accept", "*/*");
            connection.connect();
            in = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
            //这里如果不加编码方式，解析请求回来的json可能中文乱码报错
            String line;
            while ((line = in.readLine()) != null) {
                line = new String(line.getBytes(), "utf-8");
                //System.out.println(line+"<------line");
                result = line;
                //System.out.println(in.readLine()+"========"+result);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

    //通过临时授权码获取用户userId
    public static String getUserIdByCode(String code) {
        String access_token=getAccess_token();
        String url="https://oapi.dingtalk.com/user/getuserinfo?access_token="+access_token+"&code="+code;
        String result =getData(url);

        JSONObject map = JSON.parseObject(result);
        //System.out.println(map+"<----map");
        String userId = map.getString("userid");
        System.out.println(userId+"<----userId");
        return userId;
    }

    //获取人员详情二
    public static Emp getEmpDetail(String userid) {
        Emp emp = new Emp();
        emp.setUserId(userid);
        String access_token=getAccess_token();
        String url="https://oapi.dingtalk.com/user/get?access_token="+access_token+"&userid="+userid;
        String result =getData(url);
        JSONObject parseObject = JSON.parseObject(result);
        JSONArray roles = parseObject.getJSONArray("roles");
        JSONArray department = parseObject.getJSONArray("department");
        ArrayList<String> deptArray =new ArrayList<>();
        if (department.size()>0){
            for (int j = 0; j < department.size(); j++) {
                String e = department.get(j).toString();
                deptArray.add(e);
            }
        }

        emp.setDeptIdList(deptArray);
        ArrayList<EmpRoles> roleArray =new ArrayList<>();
        if(roles!=null&&roles.size()>0){
            for (int i = 0; i < roles.size(); i++) {
                Map map2 = roles.getObject(i, Map.class);
                String groupName = map2.get("groupName").toString();
                String roleName = map2.get("name").toString();
                String roleId = map2.get("id").toString();
                EmpRoles empRoles = new EmpRoles();
                empRoles.setGroupName(groupName);
                empRoles.setRoleId(roleId);
                empRoles.setRoleName(roleName);
                roleArray.add(empRoles);
            }

        }
        emp.setRoleArray(roleArray);
        /*Map map = JSON.parseObject(result,Map.class);
        String userName = map.get("name").toString();*/
        String userName = parseObject.getString("name");
        emp.setUserName(userName);
        //String avatar = map.get("avatar").toString();
        String avatar = parseObject.getString("avatar");
        emp.setAvatar(avatar);
        //String mobile = map.get("mobile").toString();
        String mobile = parseObject.getString("mobile");
        emp.setMobile(mobile);
        //String position = map.get("position").toString();
        String position = parseObject.getString("position");
        emp.setPosition(position);
        //String isLeaderInDepts = map.get("isLeaderInDepts").toString();
        String isLeaderInDepts = parseObject.getString("isLeaderInDepts");
        isLeaderInDepts = isLeaderInDepts.substring(1, isLeaderInDepts.length()- 1);
        //System.out.println(isLeaderInDepts+"----isLeaderInDepts");
        String[] split = isLeaderInDepts.split(",");
        ArrayList<String> leaderDepts = new ArrayList<String>();
        Boolean isLeader=false;
        for (String a:split) {
            if (a.endsWith(":true")) {
                leaderDepts.add(a.substring(0, a.length() - ":true".length()));
                isLeader=true;
            }
        }
        emp.setIsLeaderInDepts(isLeader);
        emp.setLeaderDeptIdList(leaderDepts);
        String isBoss = parseObject.getString("isBoss");
        String email = parseObject.getString("email");
        String isAdmin = parseObject.getString("isAdmin");
        String isSenior = parseObject.getString("isSenior");
       /* String isBoss = map.get("isBoss").toString();
        String email = map.get("email").toString();
        String isAdmin = map.get("isAdmin").toString();
        String isSenior = map.get("isSenior").toString();
       System.out.println(userName+","+avatar+","+mobile+","+email+","+isBoss);*/
        emp.setEmail(email);
        if("false".equals(isSenior)) {
            emp.setIsSenior(false);
        }else if("true".equals(isSenior)) {
            emp.setIsSenior(true);
        }
        if("false".equals(isAdmin)) {
            emp.setIsAdmin(false);
        }else if("true".equals(isAdmin)) {
            emp.setIsAdmin(true);
        }
        if("false".equals(isBoss)) {
            emp.setIsBoss(false);
        }else if("true".equals(isBoss)) {
            emp.setIsBoss(true);
        }
        System.out.println(emp+"<----------emp");
        return emp;
    }



/*
    //免登
    public HashMap<String, Object> login(String authCode){
        HashMap<String, Object> resMap = new HashMap<>();
        System.out.println(authCode+"-----authCode");
        String userId = getUserIdByCode(authCode);
        Emp empDetail = getEmpDetail(userId);
        if (empDetail !=null){
            resMap.put("data",empDetail);
        }
       return resMap;
    }

    //获取tiocket
    public static String getTicket(){
        String access_token = getAccess_token();
        String url="https://oapi.dingtalk.com/get_jsapi_ticket?"+"access_token="+access_token;
        String result =getData(url);
        JSONObject res = JSON.parseObject(result);
        String ticket="";
        if(res!=null){
            ticket=res.getString("ticket");
        }
        else{
            new Exception("Cannot resolve field ticket from oapi resonpse");
        }
        return ticket;
    }

    //签名
    public static String getSign(String ticket, String nonceStr, long timeStamp, String url) throws Exception {
        String plain = "jsapi_ticket=" + ticket + "&noncestr=" + nonceStr + "×tamp=" + String.valueOf(timeStamp)
                + "&url=" + url;
        try {
            MessageDigest sha1 = MessageDigest.getInstance("SHA-1");    //安全hash算法
            sha1.reset();
            sha1.update(plain.getBytes("UTF-8")); //根据参数产生hash值

            return bytesToHex(sha1.digest());
        } catch (NoSuchAlgorithmException e) {
            throw new Exception(e.getMessage());
        } catch (UnsupportedEncodingException e) {
            throw new Exception(e.getMessage());
        }
    }

    //将bytes类型的数据转化为16进制类型
    private static String bytesToHex(byte[] hash) {                    //将字符串转化为16进制的数据
        Formatter formatter = new Formatter();
        for (byte b : hash) {
            formatter.format("%02x", b);
        }
        String result = formatter.toString();
        formatter.close();
        return result;
    }

  */

    //6.封装好所有需要的参数，并且传递到企业应用网址的前端H5中。
    //参数:corpId,agentId,ticket,signature,nonceStr,timeStamp,url.
    //其中nonceStr,timeStamp,url用来在服务器后台生成signatrue签名，
    // 然后将ticket,nonceStr,timeStamp和signatrue传送到前台，前台网页就会
    //调用jsapi的dd.config函数重新生成signatrue,和传进的signatrue进行比较，来实现验证过程。
    /*
     * 将所有需要传送到前端的参数进行打包，在前端会调用jsapi提供的dd.config接口进行签名的验证
     *params:
     *	request:在钉钉中点击微应用图标跳转的url地址
     *return:
     *	将需要的参数打包好，按json格式打包
     */
    /*
     *以http://localhost/test.do?a=b&c=d为例
     *request.getRequestURL的结果是http://localhost/test.do
     *request.getQueryString的返回值是a=b&c=d
     */
    /*
    public static HashMap<String, Object> getConfig(HttpServletRequest request) {
        String urlString = request.getRequestURL().toString();
        String queryString = request.getQueryString();
        String url = null;
        if (queryString != null) {
            url = urlString + queryString;
        } else {
            url = urlString;
        }
        String corpId2 = corpId;
        //一些比较重要的不变得参数本人存储在properties文件中
        String corpSecret2 =corpSecret;
        String nonceStr2 =nonceStr;
        String agentId2 = agentId;    //agentid参数
        long timeStamp = System.currentTimeMillis() / 1000;     //时间戳参数
        String signedUrl = url;           //请求链接的参数，这个链接主要用来生成signatrue，并不需要传到前端
        String ticket = null;                                   //ticket参数
        String signature = null;                                //签名参数
        try {
            ticket = getTicket();
            signature = getSign(ticket, nonceStr2, timeStamp, signedUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }
        HashMap<String, Object> resMap = new HashMap<>();
        resMap.put("jsticket",ticket);
        resMap.put("signature",signature);
        resMap.put("nonceStr",nonceStr2);
        resMap.put("timeStamp",timeStamp);
        resMap.put("corpId",corpId2);
        resMap.put("agentId",agentId2);
        System.out.println(JSON.toJSONString(resMap));
        return resMap;
    }


*/
}